package com.example.productdemo.demos.conf;

import io.seata.core.model.GlobalStatus;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;

/**
 * actuator自定义health组件 - seata
 *
 * @author zdm
 * @date 2024/4/7
 */
@Component
@Slf4j
public class SeataHealthIndicator extends AbstractHealthIndicator {


	@Override
	protected void doHealthCheck(Health.Builder builder) throws Exception {
		/*
		DefaultResourceManager seataResourceManager = DefaultResourceManager.get();
		// datasource数据源
		Map<String, Resource> managedResources = seataResourceManager.getManagedResources();
		if (CollectionUtils.isEmpty(managedResources)) {
			builder.down();
		} else {
			builder.up();
		}

		TransactionManager transactionManager = TransactionManagerHolder.get();
		if (ObjectUtils.isEmpty(transactionManager)) {
			builder.down();
		} else {
			builder.up();
		}
		 */

		GlobalTransaction transaction = GlobalTransactionContext.getCurrentOrCreate();
		try {
			transaction.begin(500, "seata_heart_beat");
			GlobalStatus status = transaction.getStatus();
			log.debug("seata_heart_beat, status:{}", status);

			transaction.rollback();
			builder.up();
		} catch (Exception txx) {
			GlobalStatus status = transaction.getStatus();
			log.error("seata_heart_beat error, status:{}", status, txx);
			builder.outOfService().withDetail("seata_heart_beat", txx.getMessage());
		}
    }

}

